#include "xlcomm/base/count_down_latch.h"

namespace xlcomm {

CountDownLatch::CountDownLatch(int count) : count_(count) {}

void CountDownLatch::WaitZero() {
  std::unique_lock<std::mutex> lock(mutex_);
  while (count_ > 0) {  // 必须用while，避免假唤醒
    condition_.wait(lock);  // 条件变量配合unique_lock使用（wait内部释放锁）
  }
}

void CountDownLatch::CountDown() {
  std::lock_guard<std::mutex> lock(mutex_);
  --count_;
  if (count_ == 0) {
    condition_.notify_all();
  }
}

int CountDownLatch::count() const {
  std::lock_guard<std::mutex> lock(mutex_);
  return count_;
}

}  // namespace xlcomm